

import ij.IJ;
import ij.ImagePlus;
import ij.gui.NewImage;
import ij.plugin.filter.PlugInFilter;
import ij.process.Blitter;
import ij.process.ImageProcessor;

import pluginUtils.Complexe; 

import java.util.Random; 

/**
 * 
 */

/**
 * @author Francesco
 *
 */
public class anamor2_ implements PlugInFilter {
	private int imgCols; 
	private int imgRows;
	
	/* (non-Javadoc)
	 * @see ij.plugin.filter.PlugInFilter#run(ij.process.ImageProcessor)
	 */
	public void run(ImageProcessor ip) {
		 //get width, height and the region of interest
			this.imgCols = ip.getWidth();     
			this.imgRows = ip.getHeight();  
			
			// create a new image with the same size
			ImagePlus inverted = NewImage.createRGBImage ("New image", this.imgCols, this.imgRows, 1, NewImage.FILL_BLACK);
			ImageProcessor inv_ip = inverted.getProcessor();
			inv_ip.copyBits(ip,0,0,Blitter.COPY);

			int[] basepixels = (int[]) inv_ip.getPixels();
			int[] pixels=new int[this.imgCols*this.imgRows];
			
			
			
			double t=506.0;
			double r=-t/this.imgRows; 
			double s=(this.imgCols+r*this.imgRows)/this.imgCols; 
			
			double w=32.0;
			double v=-w/this.imgCols;
			double u=(500.0+v*this.imgCols)/this.imgRows; 
			
			
			
			
			System.out.println(this.imgRows+" "+this.imgCols);
			System.out.println(w);
			
			
			    for(int xrow=0;xrow<imgRows;xrow++){
			    	for(int ycol=0;ycol<imgCols;ycol++){
			    		double xcord=u*xrow+v*ycol+w; 
			    		double ycord=r*xrow+s*ycol+t; 
			    		int newX=(int)xcord; 
			    		int newY=(int)ycord; 
			    		if((xrow+ycol==0) // A
			    			||((xrow==0)&&(ycol==imgCols-1)) // B
			    			|| ((xrow==imgRows-1)&&(ycol==0)) //D
			    			|| ((xrow==imgRows-1)&& (ycol==imgCols-1))) //C
			    		System.out.println(xrow+" "+ycol+"-->"+newX+" "+newY); 
			    		
			    		try{
				    		if((newX<imgRows)&&(newY<imgCols)&&(newX>=0)&&(newY>=0))
				    			if(newX*imgCols+newY<imgRows*imgCols)
				    				pixels[(int)(newX*imgCols+newY)]=basepixels[xrow*imgCols+ycol];
				    	}
			    		catch(Exception e){System.err.println("Index out of bounds");}
			    		
			    	}// for ycol
			    
			    }
			 inv_ip.setPixels(pixels); 
			 inverted.show();
			 inverted.updateAndDraw();
	
			    	
}
	
	
			
	

	/* (non-Javadoc)
	 * @see ij.plugin.filter.PlugInFilter#setup(java.lang.String, ij.ImagePlus)
	 */
	
	public int setup(String arg, ImagePlus imp) {
		if (arg.equals("about"))
			{showAbout(); return DONE;}
	            return DOES_RGB+NO_CHANGES;

	}
	
	void showAbout() {
		IJ.showMessage("Droste effect",
			"Escher-like droste effect"
		); 

	}
}